<template>
  <div class="app-container">
    <div v-show="divShow === 'query'">
      <el-row v-if="searchToggle" :gutter="20">
        <el-col>
          <el-form :inline="true" @submit.native.prevent>
            <el-form-item label="用户名称">
              <el-input
                v-model="queryParams.queryText"
                placeholder="请输入用户名称"
                clearable
                prefix-icon="el-icon-search"
                @keyup.enter.native="handleQuery"
                @clear="handleQuery"
              />
            </el-form-item>
            <el-form-item label="账号状态">
              <el-select
                v-model="queryParams.enabled"
                filterable
                placeholder="请选择账号状态"
                @change="getList"
              >
                <el-option :label="'全部账号状态'" :value="-1" />
                <el-option
                  v-for="item in isTrueList"
                  :key="item.optionId"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="接单状态">
              <el-select
                v-model="queryParams.isTack"
                filterable
                placeholder="请选择接单状态"
                @change="getList"
              >
                <el-option :label="'全部接单状态'" :value="-1" />
                <el-option
                  v-for="item in isTackList"
                  :key="item.optionId"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" @click="handleReset"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row type="flex" class="mb8">
        <el-button
          v-permission="['PRIV_USERS_CREATE']"
          type="primary"
          size="mini"
          @click="OpenAddBox"
          >新增用户</el-button
        >
        <!-- <el-button
          v-permission="['PRIV_USERS_DELETE']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          >删除用户</el-button
        > -->
        <!-- <el-dropdown trigger="click" style="margin-left: 10px">
          <el-button type="primary" icon="el-icon-unlock">
            设置启用<i class="el-icon-arrow-down el-icon--right" />
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleEnableUsers"
              >启用选中记录</el-dropdown-item
            >
            <el-dropdown-item @click.native="handleDisabledUsers"
              >禁用选中记录</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown> -->
        <el-button-group style="margin-left: auto">
          <el-button
            size="mini"
            plain
            type="info"
            icon="el-icon-search"
            @click="handleSearch"
          />
          <el-button size="mini" icon="el-icon-refresh" @click="handleQuery" />
        </el-button-group>
      </el-row>

      <el-row>
        <el-table
          ref="userTable"
          v-loading="loading"
          :data="userTable.dataSource"
          row-key="id"
          stripe
          border
          :height="tableHeight * 0.65"
          :default-sort="{ prop: queryParams.orderby, order: queryParams.sort }"
          @sort-change="handleSortable"
        >
          <el-table-column
            sortable
            type="selection"
            width="55"
            align="center"
          />
          <el-table-column
            sortable
            prop="phone"
            align="center"
            label="登录账号(手机号)"
            width="150"
          />
          <el-table-column
            sortable
            prop="userName"
            :show-overflow-tooltip="true"
            align="center"
            label="用户名称"
          />
          <!-- <el-table-column sortable prop="phone" align="center" label="手机号" /> -->
          <el-table-column
            sortable
            prop="nickName"
            align="center"
            label="昵称"
          />
          <el-table-column
            sortable
            prop="sex"
            align="center"
            label="性别"
            width="80"
          />
          <el-table-column
            sortable
            prop="createTime"
            align="center"
            :show-overflow-tooltip="true"
            label="创建时间"
          />
          <el-table-column
            sortable
            prop="enabled"
            align="center"
            label="是否启用"
            width="100"
          >
            <template slot-scope="scope">
              <i
                :style="scope.row.enabled === 1 ? 'color:green' : 'color:red'"
                :class="
                  scope.row.enabled === 1 ? 'el-icon-success ' : 'el-icon-error'
                "
              />
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="remark"
            align="center"
            label="备注"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <i
                :style="scope.row.enabled === true ? 'color:green' : 'color:red'"
                :class="scope.row.enabled === true ? 'el-icon-success ' : 'el-icon-error'"
              />
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                class="edit_list_btn list_btn"
                v-permission="['PRIV_USERS_UPDATE']"
                type="info"
                size="mini"
                @click="OpenEdit(scope.row)"
                >编辑</el-button
              >
              <!--  icon="el-icon-delete" -->
              <el-button
                class="del_list_btn list_btn"
                v-permission="['PRIV_USERS_RESETPASSWD']"
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                >删除账号</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-row>
      <!-- 重置密码对话框 -->
      <el-dialog
        title="重置密码"
        :visible.sync="openPassword"
        width="800px"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-form
          ref="passwordForm"
          :model="passwordForm"
          :rules="passwordRules"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="新密码" prop="password">
                <el-input
                  v-model="passwordForm.password"
                  maxlength="50"
                  placeholder="请输入新密码"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  maxlength="50"
                  placeholder="请再次输入新密码"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitPasswordForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <vxe-modal
        v-model="employeesBox"
        width="700"
        :mask="false"
        :lockView="false"
        class="employees_box"
      >
        <template #title>
          <span>新增员工</span>
        </template>
        <template #default>
          <el-form
            ref="ticketForm"
            :model="addData"
            :rules="addDataRules"
            label-width="120px"
          >
            <el-row class="add_user_box">
              <el-col :span="12">
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input
                    v-model="addData.nickName"
                    ref="nickNameInput"
                    @keyup.enter.native="ChangeInput('userNameInput')"
                    maxlength="50"
                    placeholder="请输入用户昵称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="userName">
                  <el-input
                    v-model="addData.userName"
                    @keyup.enter.native="ChangeInput('identityCardInput')"
                    ref="userNameInput"
                    maxlength="50"
                    placeholder="请输入真实姓名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证" prop="identityCard">
                  <el-input
                    v-model="addData.identityCard"
                    placeholder="请输入身份证"
                    ref="identityCardInput"
                    @keyup.enter.native="ChangeInput('phoneInput')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="addData.phone"
                    @keyup.enter.native="ChangeInput('roleIdInput')"
                    ref="phoneInput"
                    maxlength="50"
                    placeholder="请输入手机号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属角色" prop="roleId">
                  <el-select
                    v-model="addData.roleId"
                    filterable
                    placeholder="请选择所属角色"
                    ref="roleIdInput"
                    @keyup.enter.native="
                      ChangeInput('deptIDInput', 'roleIdInput')
                    "
                  >
                    <el-option
                      v-for="item in userRoleTable"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属部门 " prop="deptID">
                  <el-select
                    v-model="addData.deptID"
                    filterable
                    ref="deptIDInput"
                    placeholder="请选择所属部门"
                    @change="GetGroup"
                    @keyup.enter.native="
                      ChangeInput('groupIDInput', 'deptIDInput')
                    "
                  >
                    <el-option
                      v-for="item in departmentList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属分组 " prop="groupID">
                  <!-- <el-input v-model="addData.groupID" placeholder="请输入是否启用" /> -->
                  <el-select
                    v-model="addData.groupID"
                    filterable
                    ref="groupIDInput"
                    placeholder="请选择所属分组"
                    @keyup.enter.native="
                      ChangeInput('remarkInput', 'groupIDInput')
                    "
                  >
                    <el-option
                      v-for="item in groupingList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12"> </el-col>
              <el-col :span="12">
                <el-form-item label="是否启用" prop="enabled">
                  <el-radio-group v-model="addData.enabled">
                    <el-radio
                      :label="item.value"
                      v-for="item in isTrueList"
                      :key="item.optionId"
                    >
                      {{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label=" 是否接单" prop="isTack">
                  <el-radio-group v-model="addData.isTack">
                    <el-radio
                      :label="item.value"
                      v-for="item in isTackList"
                      :key="item.optionId"
                    >
                      {{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="地址信息" prop="address">
                  <el-input
                    clearable
                    v-model="addData.address"
                    ref="addressInput"
                    @focus="OpenAddress()"
                    placeholder="请输入地址"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注 " prop="remark">
                  <el-input
                    v-model="addData.remark"
                    ref="remarkInput"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入备注 "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24" class="flex-box l-c-c">
                <el-button type="primary" @click="SubmitFormTicket"
                  >确 定</el-button
                >
                <el-button @click="employeesBox = false">取 消</el-button>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </vxe-modal>
      <vxe-modal
        v-model="employeesBoxEdit"
        width="900"
        :mask="false"
        :lockView="false"
        class="employees_box"
      >
        <template #title>
          <span>编辑员工</span>
        </template>
        <template #default>
          <el-tabs
            type="border-card"
            v-model="employeeTab"
            @tab-click="GetPower"
          >
            <el-tab-pane label="用户信息" name="userInfo">
              <el-form
                ref="editForm"
                :model="editData"
                :rules="editDataRules"
                label-width="120px"
              >
                <el-row class="add_user_box">
                  <el-col :span="12">
                    <el-form-item label="用户昵称" prop="nickName">
                      <el-input
                        v-model="editData.nickName"
                        ref="nickNameInput"
                        @keyup.enter.native="ChangeInput('userNameInput')"
                        maxlength="50"
                        placeholder="请输入用户昵称"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="真实姓名" prop="userName">
                      <el-input
                        v-model="editData.userName"
                        @keyup.enter.native="ChangeInput('identityCardInput')"
                        ref="userNameInput"
                        maxlength="50"
                        placeholder="请输入真实姓名"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="身份证" prop="identityCard">
                      <el-input
                        v-model="editData.identityCard"
                        placeholder="请输入身份证"
                        ref="identityCardInput"
                        @keyup.enter.native="ChangeInput('phoneInput')"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                      <el-input
                        v-model="editData.phone"
                        @keyup.enter.native="ChangeInput('roleIdInput')"
                        ref="phoneInput"
                        maxlength="50"
                        placeholder="请输入手机号"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属角色" prop="roleID">
                      <el-select
                        v-model="editData.roleID"
                        filterable
                        placeholder="请选择所属角色"
                        ref="roleIdInput"
                        @keyup.enter.native="
                          ChangeInput('deptIDInput', 'roleIdInput')
                        "
                      >
                        <el-option
                          v-for="(item, index) in userRoleTable"
                          :key="index + '_userRole'"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属部门 " prop="deptID">
                      <el-select
                        v-model="editData.deptID"
                        filterable
                        ref="deptIDInput"
                        placeholder="请选择所属部门"
                        @change="GetGroup"
                        @keyup.enter.native="
                          ChangeInput('groupIDInput', 'deptIDInput')
                        "
                      >
                        <el-option
                          v-for="(item, index) in departmentList"
                          :key="index + '_department'"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属分组 " prop="groupID">
                      <el-select
                        v-model="editData.groupID"
                        filterable
                        ref="groupIDInput"
                        placeholder="请选择所属分组"
                        @keyup.enter.native="
                          ChangeInput('remarkInput', 'groupIDInput')
                        "
                      >
                        <el-option
                          v-for="(item, index) in groupingList"
                          :key="index + '_grouping'"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12"> </el-col>
                  <el-col :span="12">
                    <el-form-item label="是否启用" prop="enabled">
                      <el-radio-group v-model="editData.enabled">
                        <el-radio
                          :label="item.value"
                          v-for="item in isTrueList"
                          :key="item.value + '_enabled'"
                        >
                          {{ item.label }}</el-radio
                        >
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label=" 是否接单" prop="isTack">
                      <el-radio-group v-model="editData.isTack">
                        <el-radio
                          :label="item.value"
                          v-for="item in isTackList"
                          :key="item.optionId"
                        >
                          {{ item.label }}</el-radio
                        >
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="地址信息" prop="address">
                      <el-input
                        clearable
                        v-model="editData.address"
                        ref="addressInput"
                        @focus="OpenAddress()"
                        placeholder="请输入地址"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="备注 " prop="remark">
                      <el-input
                        v-model="editData.remark"
                        ref="remarkInput"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入备注 "
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" class="flex-box l-c-c">
                    <el-button type="primary" @click="SubmitFormEdit"
                      >确 定</el-button
                    >
                    <el-button @click="employeesBoxEdit = false"
                      >取 消</el-button
                    >
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="配置管理" :name="'roleInfo'">
              <!--  v-loading="loadingPower" -->
              <el-table
                :data="powerList"
                row-key="id"
                height="450"
                stripe
                border
              >
                <el-table-column type="index" label="#" align="center" />
                <el-table-column prop="page" label="页面名称" width="200" />
                <el-table-column prop="role" label="权限列表">
                  <template slot-scope="scope">
                    <el-checkbox
                      v-for="item in scope.row.powers"
                      :key="item.id"
                      v-model="item.checked"
                      :class="size"
                      :label="item.description"
                      :disabled="item.disabled"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-col :span="24" class="flex-box l-c-c list_power_btn">
                <el-button type="primary" @click="SubmitPowerEdit"
                  >确 定</el-button
                >
                <el-button @click="employeesBoxEdit = false">取 消</el-button>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="登录记录" :name="'logionRecording'">
              <!--  v-loading="loadingPower" -->
              <el-table :data="loginRecordingList" height="450" stripe border>
                <!-- <el-table-column type="index" label="#" align="center" /> -->
                <el-table-column
                  prop="addTime"
                  label="时间"
                  width="130"
                  align="center"
                />
                <el-table-column prop="ipAddress" label="IP" width="110" />
                <el-table-column prop="netAddress" label="地点" />
                <el-table-column
                  prop="sessionID"
                  label="标识"
                  width="240"
                  align="center"
                />
                <el-table-column prop="role" label="请求UA" width="200">
                  <template slot-scope="scope">
                    <div v-if="scope.row.userAgent">
                      {{ scope.row.userAgent }}
                    </div>
                    <div v-else>- - - -</div>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="role" label="权限列表">
                  <template slot-scope="scope">
                    <el-checkbox
                      v-for="item in scope.row.powers"
                      :key="item.id"
                      v-model="item.checked"
                      :class="size"
                      :label="item.description"
                      :disabled="item.disabled"
                    />
                  </template>
                </el-table-column> -->
              </el-table>
              <el-col
                :span="24"
                class="flex-box l-c-c list_power_btn"
                v-if="employeeTab != 'logionRecording'"
              >
                <el-button type="primary" @click="SubmitPowerEdit"
                  >确 定</el-button
                >
                <el-button @click="employeesBoxEdit = false">取 消</el-button>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="操作日志" :name="'operateRecording'">
              <!--  v-loading="loadingPower" -->
              <el-table :data="operateRecordingList" height="450" stripe border>
                <!-- <el-table-column type="index" label="#" align="center" /> -->
                <el-table-column
                  prop="addTime"
                  label="时间"
                  width="130"
                  align="center"
                />
                <el-table-column prop="ipAddress" label="IP" width="110" />
                <el-table-column prop="netAddress" label="地点" />
                <el-table-column
                  prop="sessionID"
                  label="标识"
                  width="240"
                  align="center"
                />
                <el-table-column prop="content" label="内容" width="200">
                  <template slot-scope="scope">
                    <div v-if="scope.row.content">
                      {{ scope.row.content }}
                    </div>
                    <div v-else>- - - -</div>
                  </template>
                </el-table-column>
                <!-- <el-table-column prop="role" label="权限列表">
                  <template slot-scope="scope">
                    <el-checkbox
                      v-for="item in scope.row.powers"
                      :key="item.id"
                      v-model="item.checked"
                      :class="size"
                      :label="item.description"
                      :disabled="item.disabled"
                    />
                  </template>
                </el-table-column> -->
              </el-table>
              <el-col
                :span="24"
                class="flex-box l-c-c list_power_btn"
                v-if="employeeTab != 'logionRecording'"
              >
                <el-button type="primary" @click="SubmitPowerEdit"
                  >确 定</el-button
                >
                <el-button @click="employeesBoxEdit = false">取 消</el-button>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </template>
      </vxe-modal>
      <AddressInput ref="addressBox" @GetAddress="GetAddress"></AddressInput>
    </div>
  </div>
</template>
<script>
import {
  operateRecording,
  logionRecording,
  editUsersPower,
  queryUsers,
  createUser,
  updateUser,
  getUsersPower,
  deleteUsers,
  enableUsers,
  resetPassword,
  getUsers,
} from "@/api/users/users";
/** */
import { queryRole } from "@/api/users/roles";
import { GetRelationTree, UpdateUserRelation } from "@/api/system/authorize";
import AddressInput from "@/components/AddressInput/index.vue";
import {
  getDepartmentList,
  // @ts-ignore
} from "@/api/users/department";
import {
  getGrouping,
  // @ts-ignore
} from "@/api/users/grouping";
import {
  GetValueList,
  // @ts-ignore
} from "@/api/system/options";
/**获取所有权限 */
import {
  getPowersGroup,
  getRolePowers,
  updateRolePowers,
} from "@/api/users/rolepowers";
import { CheckPsidno } from "@/api/usualApi/index";
export default {
  components: {
    AddressInput,
  },
  computed: {
    size() {
      return this.$store.getters.size;
    },
  },
  name: "users",
  data() {
    /**校验身份证号是否正确 */
    var InspectionIdentityCard = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入身份证号"));
      } else if (!CheckPsidno(value)) {
        callback(new Error("请输入正确的身份证号"));
      } else {
        callback();
      }
    };
    return {
      /**员工对话框标题 */
      titleName: "",
      /**员工对话框内标签页选中 */
      employeeTab: "userInfo",
      /**员工对话框 */
      employeesBox: false,
      /**编辑对话框开关 */
      employeesBoxEdit: false,
      /**新增 */
      addData: {
        /** 用户名称 */
        userName: "",
        /**用户昵称 */
        nickName: "",
        /**手机号码  */
        phone: "",
        /**地址 */
        address: "",
        /**备注  */
        remark: "",
        /**身份证 */
        identityCard: "",
        /**是否接单 */
        isTack: 0,
        /** 是否启用*/
        enabled: 1,
        /**角色编号 */
        roleId: "",
        /**部门编号 */
        deptID: "",
        /**分组编号 */
        groupID: null,
        /**省 */
        province: "",
        provinceID: "",
        /**市 */
        city: "",
        cityID: "",
        /**区 */
        county: "",
        countyID: "",
      },
      /**编辑 */
      editData: {},
      // 遮罩层
      loading: false,
      // 默认选项卡
      activeName: "userInfo",
      // 表格高度
      tableHeight: window.innerHeight,
      // 单选框
      radio: "1",
      // 搜索条显示
      searchToggle: true,
      // 合计条数
      total: 0,
      // 用户信息弹出框
      divShow: "query",
      // 修改密码弹出框
      openPassword: false,
      // 查询参数
      queryParams: {
        queryText: undefined,
        pageIndex: 1,
        pageSize: 10,
        orderby: "createTime",
        sort: "descending",
        deptIDs: [],
        enabled: -1,
        isTack: -1,
      },
      /**部门列表 */
      departmentList: [],
      /**是否启用列表 */
      isTrueList: [],
      /**是否接单列表 */
      isTackList: [],
      /**分组列表 */
      groupingList: [],
      // 用户列表
      userTable: [],
      // 用户角色列表
      userRoleTable: [],
      // 删除用户列表
      delSelections: [],
      // 查询用户列表
      userSelections: [],
      // 用户权限树
      relationTree: [],
      // 用户角色
      userRole: [],
      // 表单
      form: {},
      /**编辑的个人权限列表 */
      powerList: [],
      // 密码表单
      passwordForm: {},
      // 表单标题
      title: "",
      // 表单校验
      addDataRules: {
        userName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请选择地址信息", trigger: "blur" },
        ],
        roleId: [
          { required: true, message: "请选择所属角色", trigger: "blur" },
        ],
        deptID: [
          { required: true, message: "请选择所属部门", trigger: "blur" },
        ],
        // groupID: [{ required: true, message: "请选择所属分组", trigger: "blur" }],
        enabled: [
          { required: true, message: "请选择是否启用", trigger: "blur" },
        ],
        isTack: [
          { required: true, message: "请选择是否接单", trigger: "blur" },
        ],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        identityCard: [
          {
            required: true,
            validator: InspectionIdentityCard,
            trigger: "blur",
          },
        ],
        // password: [
        //   { required: true, message: "用户密码不能为空", trigger: "blur" },
        //   { min: 6, message: "用户密码长度至少6位", trigger: "blur" }
        // ],
        // sex: [{ required: true, message: "性别不能为空", trigger: "blur" }]
      },
      /**编辑的表格校验 */
      editDataRules: {
        userName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "请选择地址信息", trigger: "blur" },
        ],
        roleId: [
          { required: true, message: "请选择所属角色", trigger: "blur" },
        ],
        deptID: [
          { required: true, message: "请选择所属部门", trigger: "blur" },
        ],
        // groupID: [{ required: true, message: "请选择所属分组", trigger: "blur" }],
        enabled: [
          { required: true, message: "请选择是否启用", trigger: "blur" },
        ],
        isTack: [
          { required: true, message: "请选择是否接单", trigger: "blur" },
        ],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        identityCard: [
          {
            required: true,
            validator: InspectionIdentityCard,
            trigger: "blur",
          },
        ],
      },
      // 重置密码表单校验
      passwordRules: {
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 6, message: "用户密码长度至少6位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { min: 6, message: "用户密码长度至少6位", trigger: "blur" },
        ],
      },
      // 重置密码用户
      ResetPasswordUserId: "",
      // 过滤查询
      search: "",
      /**单个账号登录记录 */
      loginRecordingList: [],
      /**单个账号操作记录 */
      operateRecordingList: [],
      defaultProps: {
        children: "children",
        label: "relationName",
      },
    };
  },
  created() {
    this.InitialData();
  },
  methods: {
    /**打开新增员工对话框 */
    OpenAddBox() {
      this.titleName = "新增员工";
      this.employeesBox = true;
      // console.log(this.employeesBox);
    },
    /**
     * 确认新增
     */
    SubmitFormTicket() {
      this.$refs.ticketForm.validate(async (valid) => {
        if (valid) {
          let { statusCode } = await createUser(this.addData);
          if (statusCode != 200) return;
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.employeesBox = false;
          this.addData = {
            userName: "",
            nickName: "",
            phone: "",
            address: "",
            remark: "",
            identityCard: "",
            isTack: "0",
            enabled: "1",
            roleId: "",
            deptID: "",
            groupID: null,
          };
          this.getList();
        }
      });
    },
    /**打开地址选择地址 */
    OpenAddress() {
      this.$refs.addressBox.OpenAddress();
    },
    /**接收地址选择回传的数据 */
    GetAddress(row) {
      if (this.employeesBox) {
        this.addData.address = row.spellingText;
        this.addData.provinceID = row.provinceId;
        this.addData.cityID = row.cityId;
        this.addData.countyID = row.districtId;
        this.addData.province = row.province;
        this.addData.city = row.city;
        this.addData.county = row.district;
        this.addData.streetID = row.streetId;
        this.addData.street = row.street;
      } else if (this.employeesBoxEdit) {
        this.editData.address = row.spellingText;
        this.editData.provinceID = row.provinceId;
        this.editData.cityID = row.cityId;
        this.editData.countyID = row.districtId;
        this.editData.province = row.province;
        this.editData.city = row.city;
        this.editData.county = row.district;
        this.editData.streetID = row.streetId;
        this.editData.street = row.street;
      }
    },
    /**切换下一个input */
    ChangeInput(text, name = null) {
      if (name != null) {
        this.$refs[name].blur();
      }
      this.$refs[text].focus();
    },
    /**根据部门获取分组 */
    async GetGroup(id) {
      /**分组列表 */
      let res = await getGrouping({
        name: "",
        deptID: id,
        orderBy: "createTime",
        sort: "descending",
        pageIndex: 1,
        pageSize: 2000,
      });
      if (res.statusCode != 200) return;
      if (this.employeesBox) {
        this.addData.groupID = null;
      } else if (this.employeesBoxEdit) {
        this.editData.groupID = null;
      }
      this.groupingList = res.data.dataSource;
    },
    /**初始数据函数 */
    async InitialData() {
      /**角色列表 */
      let {
        data: { dataSource },
        statusCode,
      } = await queryRole({
        name: undefined,
        pageIndex: 1,
        pageSize: 1000,
        orderby: "createTime",
        sort: "ascending",
      });
      if (statusCode != 200) return;
      /**部门列表 */
      let row = await getDepartmentList({
        name: "",
        enabled: -1,
        orderBy: "createTime",
        sort: "descending",
        pageIndex: 1,
        pageSize: 1000,
      });
      if (row.statusCode != 200) return;
      this.departmentList = row.data.dataSource;

      /**是否接单 */
      let json = await GetValueList("Enabled");
      if (json.statusCode != 200) return;
      json.data.forEach((item) => {
        if (item.dataType == "int") {
          item.value = parseInt(item.value);
        }
      });
      this.isTrueList = json.data;
      /**是否接单 */
      let tack = await GetValueList("CustomerTackState");
      if (tack.statusCode != 200) return;
      tack.data.forEach((item) => {
        if (item.dataType == "int") {
          item.value = parseInt(item.value);
        }
      });
      this.isTackList = tack.data;

      this.getList();
      this.userRoleTable = dataSource;
    },
    /**打开编辑页面 */
    async OpenEdit(row) {
      /**角色列表 */
      let { data, statusCode } = await getUsers(row.id);
      if (statusCode != 200) return;
      // let groupId = JSON.parse(JSON.stringify(data)).groupID;
      await this.GetGroup(data.deptID);
      // data.groupID = groupId;
      this.editData = data;
      this.employeeTab = "userInfo";
      this.employeesBoxEdit = true;
    },
    /**确认编辑 */
    SubmitFormEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          let { statusCode } = await updateUser(this.editData);
          if (statusCode != 200) return;
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          this.employeesBoxEdit = false;

          this.getList();
        }
      });
    },
    /**切换编辑权限获取数据 */
    async GetPower() {
      if (this.employeeTab == "roleInfo") {
        let { data, statusCode } = await getPowersGroup();
        if (statusCode != 200) return;
        let res = await getUsersPower(this.editData.id);
        if (res.statusCode != 200) return;
        let { rolePowerIDs, userPowerIDs } = res.data;
        data.forEach((element) => {
          element.powers.forEach((item) => {
            if (rolePowerIDs.indexOf(item.id) === -1) {
              item.checked = false;
              item.disabled = false;
            } else {
              item.checked = true;
              item.disabled = true;
            }
            if (userPowerIDs.indexOf(item.id) != -1) {
              item.checked = true;
            } else {
            }
          });
        });
        this.powerList = data;
      } else if (this.employeeTab == "logionRecording") {
        let {
          data: { dataSource },
          statusCode,
        } = await logionRecording({
          pageIndex: 1,
          pageSize: 100,
          orderBy: "addTime",
          sort: "desc",
          userID: this.editData.id,
        });
        if (statusCode != 200) return;
        // console.log(dataSource);

        this.loginRecordingList = dataSource;
      } else if (this.employeeTab == "operateRecording") {
        let {
          data: { dataSource },
          statusCode,
        } = await operateRecording({
          pageIndex: 1,
          pageSize: 100,
          orderBy: "addTime",
          sort: "desc",
          userID: this.editData.id,
        });
        if (statusCode != 200) return;
        console.log(dataSource);

        this.operateRecordingList = dataSource;
      }
    },
    /**编辑保存账号个人权限 */
    async SubmitPowerEdit() {
      let list = [];
      this.powerList.forEach((item) => {
        item.powers.forEach((el) => {
          if (el.checked && !el.disabled) {
            list.push(el.id);
          }
        });
      });
      let { statusCode } = await editUsersPower({
        id: this.editData.id,
        powerIDs: list,
      });
      if (statusCode != 200) return;
      this.$message({
        message: "编辑成功",
        type: "success",
      });
      this.employeesBoxEdit = false;
    },
    handleSearch() {
      this.searchToggle = !this.searchToggle;
    },
    /** 查询用户列表 */
    async getList() {
      this.loading = true;
      let { data, statusCode } = await queryUsers(this.queryParams);
      if (statusCode != 200) return;
      this.userTable = data;
      this.total = this.userTable.totalCount;
      this.loading = false;
    },
    /** 新增按钮操作 */
    handleCreate() {
      this.reset();
      this.divShow = "edit";
      this.title = "添加用户";
      this.activeName = "userInfo";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row;
      delete this.form.password;
      this.divShow = "edit";
      this.title = "编辑用户";
      this.activeName = "userInfo";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams.queryText = "";
      this.getList();
    },
    // 删除按钮操作
    handleDelete() {
      this.delSelections = [];
      this.$refs.userTable.selection.forEach((element) => {
        this.delSelections.push(element.userID);
      });
      if (this.delSelections.length === 0) {
        return;
      }
      this.$confirm(
        "是否确认删除选中的 " + this.delSelections.length + " 条数据?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          deleteUsers({
            userIds: this.delSelections,
          }).then((response) => {
            if (response.statusCode === 200) {
              this.$message({
                message: "成功删除" + response.data + "条数据",
                type: "success",
              });
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    // 重置密码
    handleResetPassword(row) {
      this.ResetPasswordUserId = row.userID;
      this.reset();
      this.openPassword = true;
    },
    // 启用用户
    handleEnableUsers() {
      if (this.$refs.userTable.selection.length > 0) {
        this.userSelections = [];
        this.$refs.userTable.selection.forEach((element) => {
          this.userSelections.push(element.userID);
        });
        enableUsers({
          userIds: this.userSelections,
          status: true,
        }).then((response) => {
          if (response.statusCode === 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getList();
          }
        });
      } else {
        this.$message({
          message: "请至少选择一项",
          type: "warning",
        });
      }
    },
    // 禁用用户
    handleDisabledUsers() {
      if (this.$refs.userTable.selection.length > 0) {
        this.userSelections = [];
        this.$refs.userTable.selection.forEach((element) => {
          this.userSelections.push(element.userID);
        });
        enableUsers({
          userIds: this.userSelections,
          status: false,
        }).then((response) => {
          if (response.statusCode === 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getList();
          }
        });
      } else {
        this.$message({
          message: "请至少选择一项",
          type: "warning",
        });
      }
    },
    // 用户角色提交按钮
    submitRoleForm() {},
    // 用户权限提交按钮
    submitPowerForm() {
      const relation = [];
      this.$refs.relationTree.selection.forEach((val) => {
        relation.push({
          objectID: val.id,
          objectType: val.relationType,
        });
      });
      UpdateUserRelation({
        userID: this.form.userID,
        relation: relation,
      }).then((response) => {
        if (response.statusCode === 200) {
          this.$message({
            message: "更新权限成功",
            type: "success",
          });
        } else {
          this.$message.error(response.message);
        }
      });
    },
    // 用户绑定微信提交按钮
    submitWexinForm() {},
    // 排序操作
    handleSortable(val) {
      this.queryParams.orderby = val.prop;
      this.queryParams.sort = val.order;
      this.getList();
    },
    // 重置密码提交
    submitPasswordForm() {
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          if (
            this.passwordForm.password !== this.passwordForm.confirmPassword
          ) {
            this.$message.error("两次密码输入不一致");
            return;
          }
          resetPassword({
            userID: this.ResetPasswordUserId,
            confirmPassword: this.passwordForm.password,
          }).then((response) => {
            if (response.statusCode === 200) {
              this.$message({
                message: "密码重置成功",
                type: "success",
              });
              this.openPassword = false;
            } else {
              this.$message.error(response.message);
            }
          });
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        userID: undefined,
        userName: undefined,
        nickName: undefined,
        email: undefined,
        password: undefined,
        sex: "男",
        avatarUrl: undefined,
        qq: undefined,
        phone: undefined,
        provinceID: undefined,
        province: undefined,
        cityID: undefined,
        city: undefined,
        countyID: undefined,
        county: undefined,
        address: undefined,
        remark: undefined,
        identityCard: undefined,
        birthday: undefined,
        enabled: true,
        oneSession: true,
      };
      this.passwordForm = {
        password: undefined,
        confirmPassword: undefined,
      };
    },
    // 取消按钮
    cancel() {
      this.divShow = "query";
      this.openPassword = false;
      this.reset();
      this.getList();
    },
    // 全选勾选
    handleRelationTreeSelectAll() {
      this.selectionParentRowAll(this.relationTree);
    },
    // 全选
    selectionParentRowAll(data, selection) {
      if (data) {
        data.forEach((val) => {
          this.$refs.relationTree.toggleRowSelection(val, true);
          if (val.children) {
            this.selectionParentRowAll(val.children);
          }
        });
      }
    },
    // RelationTree 勾选行
    handleRelationTreeSelect(selection, row) {
      if (selection.length && selection.indexOf(row) !== -1) {
        this.selectionParentRow(row.parentUID, this.relationTree);
      } else {
        // 父节点取消时取消子节点勾选
        this.unselectionRow(row);
      }
    },
    // 递归勾选
    selectionParentRow(parentUID, data) {
      data.forEach((row) => {
        if (row.id === parentUID) {
          this.$refs.relationTree.toggleRowSelection(row, true);
          if (row.parentUID) {
            this.selectionParentRow(row.parentUID, this.relationTree);
          }
          return;
        }
        if (row.children) {
          this.selectionParentRow(parentUID, row.children);
        }
      });
    },
    // 取消勾选
    unselectionRow(row) {
      if (row.children) {
        row.children.forEach((children) => {
          this.$refs.relationTree.toggleRowSelection(children, false);
          if (children) {
            this.unselectionRow(children);
          }
        });
      }
    },
    // 用户权限修改
    handleTabsClick(val) {
      if (val.index === "1") {
        this.loading = true;
        GetRelationTree(this.form.userID).then((response) => {
          this.relationTree = response.data;
          this.selectUserRole(this.relationTree);
          this.loading = false;
        });
      }
    },
    // 匹配用户权限勾选
    selectUserRole(data) {
      if (data) {
        data.forEach((val) => {
          if (val.hasRelation) {
            this.$nextTick(() => {
              this.$refs.relationTree.toggleRowSelection(val, true);
            });
          }
          if (val) {
            this.selectUserRole(val.children);
          }
        });
      }
    },
    // row样式赋值
    tableRowClassName(row, rowIndex) {
      switch (row.row.relationType) {
        case "Company":
          return "company-row";
        case "Factory":
          return "factory-row";
        case "WorkShop":
          return "workShop-row";
        case "ProductLine":
          return "productLine-row";
        case "ProductProcess":
          return "productProcess-row";
        default:
          break;
      }
    },
  },
};
</script>
<style lang="scss" src="./index.scss"></style>
<style>
.showTable {
  background-color: #ffffff;
  width: 80%;
  height: 100%;
  margin: 25px auto;
}

.showTable .el-tabs__content {
  height: 100%;
}

.tableList {
  width: 50%;
  height: 40vh;
  position: absolute;
  top: 20%;
  left: 20%;
}

.foot {
  position: absolute;
  bottom: 15px;
  right: 15px;
}

.el-table .company-row {
  background: rgb(236, 245, 255);
}

.el-table .factory-row {
  background: rgb(240, 249, 235);
}

.el-table .workShop-row {
  background: rgb(253, 246, 236);
}

.el-table .productLine-row {
  background: rgb(254, 240, 240);
}

.el-table .productProcess-row {
  background: rgb(244, 244, 245);
}
</style>
